package com.example.tobebigfe.jsbridge

import android.content.Context
import android.net.Uri
import android.util.Log
import android.webkit.MimeTypeMap
import android.webkit.WebResourceResponse
import android.webkit.WebView
import android.webkit.WebViewClient
import com.example.tobebigfe.web.WebConst
import com.example.tobebigfe.web.WebManager
import java.io.File
import java.io.FileInputStream
import java.nio.charset.StandardCharsets

class CustomWebViewClient(val context: Context) : WebViewClient() {

    override fun shouldInterceptRequest(view: WebView, url: String): WebResourceResponse? {
        Log.e("WebView", "intercept $url")
        val uri = Uri.parse(url)
        // 解析拦截的url，判断域名
        if (uri.host == "file.local") {
            return interceptFileLocal(uri)
        }
        if (url.startsWith(WebConst.WEB_BASE_URL)) {
            return interceptWebOfflineFile(uri)
        }
        return null
    }

    private fun interceptWebOfflineFile(uri: Uri): WebResourceResponse? {
        val segs = uri.pathSegments
        if (segs.size < 4) {
            return null
        }
        val id = segs[1]
        val version = segs[2]
        val filePath = segs.subList(3, segs.size).joinToString("/")
        val file = WebManager.getOfflineFile(id, version, filePath)
        Log.e("WebView", "offline ${file.exists()} ${file.absolutePath}")
        if (file.exists()) {
            val mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(file.extension)
            val fis = FileInputStream(file)
            return WebResourceResponse(mimeType, StandardCharsets.UTF_8.name(), fis)
        }
        return null
    }

    private fun interceptFileLocal(uri: Uri): WebResourceResponse? {
        // 拿到file参数，否则也返回null
        val filePath = uri.getQueryParameter("file") ?: return null
        Log.e("WebView", "file $filePath")

        // file协议
        if (filePath.startsWith("file://")) {
            // 去掉file://前缀创建File对象
            val file = File(filePath.substring("file://".length))
            // 通过ext得到mime
            val mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(file.extension)
            // 创建FileInputStream
            val fis = FileInputStream(file)
            // 返回本地的内容的Response
            return WebResourceResponse(mimeType, StandardCharsets.UTF_8.name(), fis)
        }
        // content协议
        else if (filePath.startsWith("content://")) {
            // 创建Uri
            val fileUri = Uri.parse(filePath)
            // 获取mimeType
            val mimeType = context.contentResolver.getType(fileUri)
            // 通过contentResolver创建InputStream
            val fis = context.contentResolver.openInputStream(fileUri)
            // 返回本地的内容Response
            return WebResourceResponse(mimeType, StandardCharsets.UTF_8.name(), fis)
        }

        // 其他情况
        return null
    }

}